package com.zzy.eventbus.subdemo;

import java.util.concurrent.Executors;

import org.junit.Test;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.zzy.eventbus.subdemo.base.EventBusFactory;

public class EventBusTest {

	// 测试重复注册监听器 //会有两个一样的监听器
	@Test
	public void testRepeatRegister() {
		final EventBus bus = new EventBus();
		bus.register(new TestEventListener());
		bus.register(new TestEventListener());

		TestEvent event = new TestEvent("TEST_EVENT", "123");

		bus.post(event);
	}

	public static void main(String[] args) {
		// 对于使用的是非异步（AsyncEventBus），也建议增加@AllowConcurrentEvents，因为不需要进行同步。
		final AsyncEventBus bus = new AsyncEventBus(Executors.newFixedThreadPool(100));

		for (int i = 0; i < 100; i++) {
			final int cnt = i;
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("第" + cnt + "次");
					bus.register(new MemberDeletedEventListener());
				}
			});
			t.start();
		}

		try {
			Thread.sleep(6000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		MemberDeletedEvent event = new MemberDeletedEvent("MEMBER_DELETE_EVENT");
		bus.post(event);
	}

	// 测试并发操作
	@Test
	public void testConcurrcy() {

		MemberDeletedEvent event = new MemberDeletedEvent("MEMBER_DELETE_EVENT");

		for (int i = 0; i < 100; i++) {
			final int cnt = i;
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("第" + cnt + "次");
					EventBusFactory.build().register(MemberDeletedEventListener.class);
				}
			});
			t.start();
		}
		try {
			Thread.sleep(6000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		EventBusFactory.build().postsEvent(event);
	}

	// 测试继承结构下的事件分发
	@Test
	public void testInherit() {
		TestEvent event = new TestEvent("TEST_EVENT", "123");
		EventBusFactory.build().register(TestEventListener.class);
		EventBusFactory.build().postsEvent(event);
	}
}